#include "tianqi.h"
#include "ui_tianqi.h"
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonArray>
#include <QStandardItemModel>
#include <QDebug>
#include <QNetworkAccessManager>


tianqi::tianqi(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::tianqi)
{
    ui->setupUi(this);
    pmodel = new QStandardItemModel (12,11,ui->tableView);
    QStringList list = QStringList()<<"日期"<<"天气"<<"最高温度"<<"最低温度"<<"星期"<<"日出时间"<<"日落时间"<<"空气质量指数"<<"风向"<<"风力"<<"温馨提示";
    pmodel->setHorizontalHeaderLabels(list);
    ui->tableView->setModel(pmodel);

     manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),
                this, SLOT(replyFinished(QNetworkReply*)));
    ui->tableView->horizontalHeader();

    QHeaderView *header = ui->tableView->verticalHeader();
    header->setHidden(true);// 隐藏行号

    db = QSqlDatabase::addDatabase("QSQLITE");

}

tianqi::~tianqi()
{
    delete ui;
}
void tianqi::replyFinished(QNetworkReply* reply)
{
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
        {
            qDebug()<<"访问服务器成功"<<endl;
            parseJson(reply->readAll());
        }
}

void tianqi::parseJson(QByteArray byteArray)
{

    QJsonDocument doc = QJsonDocument::fromJson(byteArray);
    if(doc.isObject())
    {
        QString date;
        QString high;
        QString low;
        QString ymd;
        QString week;
        QString sunrise;
        QString sunset;
        int aqi;
        QString fx;
        QString fl;
        QString type;
        QString notice;
        QJsonObject obj1 = doc.object();
        if(obj1.contains("data") == false)
        {
            qDebug()<<"错误的json对象"<<endl;
            return;
        }
        QJsonValue var = obj1.value("data");

        if(var.isObject() == false)
        {
            qDebug()<<"data的值不是一个对象"<<endl;
            return;
        }
        QJsonObject dataobj = var.toObject();
        if(dataobj.contains("forecast") == false)
        {
            qDebug()<<"data中没有预报"<<endl;
            return;
        }
        var = dataobj.value("forecast");
        if(var.isArray())
        {
            QJsonArray forecastarr = var.toArray();
            qDebug()<<"一共搜索到"<<forecastarr.size()<<"天的天气"<<endl;
            for (int i = 0;i < forecastarr.size();i++)
            {
                QJsonObject forecastobj = forecastarr[i].toObject();
                if(forecastobj.contains("date"))
                {
                    QJsonValue vardate = forecastobj.value("date");
                    date = vardate.toString();
                }
                if(forecastobj.contains("high"))
                {
                    QJsonValue varhigh = forecastobj.value("high");
                    high = varhigh.toString();
                }
                if(forecastobj.contains("low"))
                {
                    QJsonValue varlow = forecastobj.value("low");
                    low = varlow.toString();
                }
                if(forecastobj.contains("ymd"))
                {
                    QJsonValue varymd = forecastobj.value("ymd");
                    ymd = varymd.toString();
                }
                if(forecastobj.contains("week"))
                {
                    QJsonValue varweek = forecastobj.value("week");
                    week = varweek.toString();
                }
                if(forecastobj.contains("sunrise"))
                {
                    QJsonValue varsunrise = forecastobj.value("sunrise");
                    sunrise = varsunrise.toString();
                }
                if(forecastobj.contains("sunset"))
                {
                    QJsonValue varsunset = forecastobj.value("sunset");
                    sunset = varsunset.toString();
                }
                if(forecastobj.contains("aqi"))
                {
                    QJsonValue varaqi = forecastobj.value("aqi");
                    aqi = varaqi.toInt();
                }
                if(forecastobj.contains("fx"))
                {
                    QJsonValue varfx = forecastobj.value("fx");
                    fx = varfx.toString();
                }
                if(forecastobj.contains("fl"))
                {
                    QJsonValue varfl = forecastobj.value("fl");
                    fl = varfl.toString();
                }
                if(forecastobj.contains("type"))
                {
                    QJsonValue vartype = forecastobj.value("type");
                    type = vartype.toString();
                }
                if(forecastobj.contains("notice"))
                {
                    QJsonValue varnotice = forecastobj.value("notice");
                    notice = varnotice.toString();
                }
                qDebug()<<date<<" "<<high<<" "<<low<<" "<<ymd<<" "<<week<<" "<<sunrise<<" "<<sunset<<" "<<aqi<<" "<<fx<<" "<<fl<<" "<<type<<" "<<notice<<endl;
                QStandardItem *item = new QStandardItem(date);

                item = new QStandardItem(high);
                pmodel->setItem(i,2,item);
                item = new QStandardItem(low);
                pmodel->setItem(i,3,item);
                item = new QStandardItem(ymd);
                pmodel->setItem(i,0,item);
                item = new QStandardItem(week);
                pmodel->setItem(i,4,item);
                item = new QStandardItem(sunrise);
                pmodel->setItem(i,5,item);
                item = new QStandardItem(sunset);
                pmodel->setItem(i,6,item);
                item = new QStandardItem(QString("%1").arg(aqi));
                pmodel->setItem(i,7,item);
                item = new QStandardItem(fx);
                pmodel->setItem(i,8,item);
                item = new QStandardItem(fl);
                pmodel->setItem(i,9,item);
                item = new QStandardItem(type);
                pmodel->setItem(i,1,item);
                item = new QStandardItem(notice);
                pmodel->setItem(i,10,item);

            }
        }

    }

}

void tianqi::on_pushButton_clicked()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); // 明确指定数据库类型为 QSQLITE
        db.setDatabaseName("mydatabase.db");

        if (!db.open())
        {
            qDebug() << "Error: Connection with database failed:" << db.lastError().text();
            return;
        }
        qDebug() << "打开成功\n";

        QSqlQuery query;
//        const QString createTableSQL = "CREATE TABLE IF NOT EXISTS Cities ("
//                                       "code TEXT NOT NULL,"
//                                       "name TEXT NOT NULL"
//                                       ")";
//        bool ok = query.exec(createTableSQL);

//        if (!ok) {
//            qDebug() << "Error: Table creation failed:" << query.lastError().text();
//            db.close();
//            return;
//        }

//        const QString insertSQL = "INSERT INTO Cities (code, name) VALUES ('101020100', '上海')";
//        ok = query.exec(insertSQL);
//        if (!ok) {
//            qDebug() << "Error: Insert failed:" << query.lastError().text();
//            db.close();
//            return;
//        }
        QString queryStr = QString("SELECT * FROM Cities WHERE name = '%1'").arg(ui->lineEdit->text());
        if (query.exec(queryStr))
        {
            while (query.next())
            {
                QString code = query.value("code").toString();
                QString name = query.value("name").toString();
                qDebug() << "code:" << code << ", Name:" << name;
                manager->get(QNetworkRequest(QUrl(QString("http://t.weather.sojson.com/api/weather/city/%1").arg(code))));

            }
        }

        db.close();
}
